<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span {
            border: 1px solid #000;
            display: inline-block;
            margin: 10px;
        }
    </style>
</head>

<body>

    <a onclick="goCart()">去购物车</a>

    <div class="box">
        <p>
            <span></span>
        </p>
    </div>




    <script src="../js/tools.js"></script>
    <script>

        // 拿到id

        const id = queryString('id');
        console.log(id);

        // 判断是否登录
        const user = localStorage.getItem('login_user');

        ajax({
            type: 'get',
            data: {
                id
            },
            path: '../php/detail.php',
            success: res => {
                console.log(res);
                const { list } = res;
                console.log(list);
                const oBox = document.querySelector('.box');
                let spans = '';

                // 重量
                if (list.goods_weight) {
                    const arr = list.goods_weight.split(',');
                    console.log(arr);

                    arr.forEach(v => {
                        spans += `<span>${v}</span>`
                    })
                    console.log(spans);
                }


                oBox.innerHTML = `
                    <img src="${list.goods_img}" alt="">
                    <h3>${list.goods_title}</h3>
                    <button onclick="addToCart()">加入购物车</button>
                    <p>${spans}</p>
                `
            }
        })





        // 加入购物车  --- 谁买了几件什么商品


        function addToCart() {

            if (user) {
                ajax({
                    type: 'post',
                    data: {
                        username: user,
                        id,
                        num: 1
                    },
                    path: '../php/addToCart.php',
                    success: res => {
                        console.log(res);
                        alert(res.msg);
                    }
                })
            } else {
                // 如果没有登录就跳转到登录页面   --- 登录成功以后还要回来
                const url = location;
                location.href = '03login.html?historyURL=' + url;
            }


        }



        // 判断是否可以进入购物车
        function goCart() {
            if(user) {
                location.href = './06cart.html'
            } else {
                location.href = '03login.html?historyURL=' + url;
            }
        }





    </script>

</body>

</html>